<template>
  <a-modal
    :title="modalTitle"
    :width="640"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <a-form-model
        :model="model"
        v-bind="formLayout"
        ref="ruleForm"
        :rules="rules"
        @submit.native.prevent>
        <a-form-model-item
          label="角色名称">
          {{ model.roleName }}
        </a-form-model-item>
        <a-form-model-item
          label="菜单项"
          prop="status">
          <a-tree
            v-model="model.authorityList"
            checkable
            :selectable="false"
            :tree-data="treeData"
            :replace-fields="replaceFields"
            @check="onCheck"
          />
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
// 表单字段
const fields = ['roleName', 'menuList']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    model: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      loading: false,
      modalTitle: '设置权限',
      rules: {},
      form: this.$form.createForm(this),
      checkedKeys: [],
      treeData: [],
      replaceFields: {
        children: 'children',
        title: 'authorityName',
        value: 'id',
        key: 'id'
      }
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
  },
  mounted () {
    this.getMenuList()
  },
  methods: {
    getMenuList () {
      this.$common.handlePost('/authorities/getListAll', {}).then(data => {
        this.loading = false
        if (data.code === 200) {
          const result = data.result
          this.treeData = result
        //   console.log(this.treeData)
        }
      })
    },
    onCheck (checkedKeys, e) {
        console.log(e)
      console.log('onCheck', checkedKeys, e.halfCheckedKeys)
      this.model.allCheckedNodes = checkedKeys.concat(e.halfCheckedKeys)
      // this.model.menuList = checkedKeys
    },
    // 弹出框-确定
    handleOk (e) {
      const {
        handleFormData
      } = this
      this.loading = true
      // 验证表单
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          handleFormData('/authorities/saveBodyAuthorities')
        } else {
          const _this = this
          setTimeout(() => {
            _this.loading = false
          }, 600)
        }
      })
    },
    // 弹出框-取消
    handleCancel (e) {
      // 重置表单数据
      this.$refs.ruleForm.resetFields()
      this.$emit('cancel')
    },
    // 表单数据处理
    handleFormData (url) {
      const info = { ...this.model }
      info.authorityList = info.allCheckedNodes

      delete info.allCheckedNodes
      delete info.roleName

      this.$common.handlePost(url, info)
        .then(res => {
          if (res.code === 200) {
            this.$message.success(res.message, 1, () => {
              // 重置表单数据
              this.$refs.ruleForm.resetFields()
              // 关闭弹框
              this.$emit('ok')
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(() => {
          this.$notification.error({
            message: '错误',
            description: '请求信息失败，请重试'
          })
        })
        .finally(() => {
          this.loading = false
        })
    }
  },
  watch: {
    model (val) {
      const indexs = [] // 父级存在，子级不都在的父级所在的索引
      this.treeData.forEach(item => {
        const index = val.authorityList.indexOf(item.id) // 父级所在的索引
        if (index !== -1) { // 查询父级是否存在
          // 查看是否所有子级都存在（筛选出不存在的）
          const arr = item.children ? item.children.filter(child => val.authorityList.indexOf(child.id) === -1) : []
          if (arr.length > 0) {
            indexs.push(index)
          }
        }
      })
      indexs.forEach(item => val.authorityList.splice(item, 1))
    }
  }
}
</script>
